<template>
  <a-modal
    :title="title"
    :width="1400"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @cancel="handleCancel"
    :footer="null">
    
    <a-spin :spinning="confirmLoading">
      <!-- 入库单基本信息 -->
      <a-card :bordered="false" title="入库单基本信息" style="margin-bottom: 16px">
        <a-descriptions bordered :column="3" size="small">
          <a-descriptions-item label="入库单号">{{ inboundOrder.inboundNo }}</a-descriptions-item>
          <a-descriptions-item label="业务类型">
            <j-dict-tag :value="inboundOrder.businessType || ''" dictCode="inventory_business_type"/>
          </a-descriptions-item>
          <a-descriptions-item label="业务单号">{{ inboundOrder.businessNo }}</a-descriptions-item>
          <a-descriptions-item label="批次号">{{ inboundOrder.batchNo }}</a-descriptions-item>
          <a-descriptions-item label="状态">
            <a-tag :color="getStatusColor(inboundOrder.status)">
              <j-dict-tag :value="inboundOrder.status || ''" dictCode="inbound_order_status"/>
            </a-tag>
          </a-descriptions-item>
          <a-descriptions-item label="入库凭证">
            <div class="upload-container">
              <j-image-upload
                v-model="inboundOrder.inboundVoucher"
                :number="5"
                :isMultiple="true"
                :bizPath="'wms/inbound'"
                :returnUrl="true"
                @change="handleVoucherChange"
                @error="handleImageError"
              ></j-image-upload>
            </div>
          </a-descriptions-item>
          <a-descriptions-item label="计划入库时间">{{ inboundOrder.planInboundTime }}</a-descriptions-item>
          <a-descriptions-item label="实际入库时间">
            <span v-if="!editingActualTime" @click="editActualTime" style="cursor: pointer;">
              {{ inboundOrder.actualInboundTime || formatCurrentDate() }}
            </span>
            <a-date-picker 
              v-else 
              v-model="inboundOrder.actualInboundTime" 
              :show-time="{ format: 'HH:mm:ss' }" 
              format="YYYY-MM-DD HH:mm:ss"
              style="width: 100%"
              @change="saveActualTime"
              @blur="cancelEditActualTime" />
          </a-descriptions-item>
          <a-descriptions-item label="创建人">{{ inboundOrder.createBy }}</a-descriptions-item>
          <a-descriptions-item label="总计划入库数量">{{ inboundOrder.totalPlanQuantity }}</a-descriptions-item>
          <a-descriptions-item label="总实际入库数量">
            <span v-if="!editingTotalActualQty" @click="editTotalActualQty" style="cursor: pointer;">
              {{ inboundOrder.totalActualQuantity || inboundOrder.totalPlanQuantity || 0 }}
            </span>
            <a-input-number 
              v-else 
              v-model="inboundOrder.totalActualQuantity" 
              :min="0" 
              :max="inboundOrder.totalPlanQuantity"
              :precision="2"
              style="width: 100%"
              @pressEnter="saveTotalActualQty"
              @blur="cancelEditTotalActualQty" />
          </a-descriptions-item>
          <a-descriptions-item label="总成本">{{ inboundOrder.totalCost }}</a-descriptions-item>
        </a-descriptions>
      </a-card>
      
      <!-- 入库单明细列表 -->
      <a-card :bordered="false" title="入库单明细列表" style="margin-bottom: 16px">
        <div class="table-operations" style="margin-bottom: 16px;">
          <a-radio-group v-model="filterType" @change="handleFilterChange">
            <a-radio-button value="all">全部明细</a-radio-button>
            <a-radio-button value="notInbound">未入库明细</a-radio-button>
            <a-radio-button value="inbound">已入库明细</a-radio-button>
          </a-radio-group>
          <span style="margin-left: 8px; color: #999;">
            <a-badge status="default" text="未入库" />
            <a-badge status="processing" text="部分入库" style="margin-left: 8px;" />
            <a-badge status="success" text="已完成入库" style="margin-left: 8px;" />
          </span>
        </div>
        <div class="table-container">
          <a-table
            :columns="columns"
            :dataSource="filteredDetailList"
            :pagination="false"
            :loading="loading"
            :scroll="{ x: 1300 }"
            :rowClassName="getRowClassName"
            :rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
            rowKey="id"
            size="middle"
            :defaultSortOrder="'ascend'"
            bordered>
            <template slot="materialTypeSlot" slot-scope="text">
              <j-dict-tag :value="text || ''" dictCode="material_type"/>
            </template>
            
            <template slot="planWarehouseSlot" slot-scope="text, record">
              <div>
                <j-select-warehouse 
                  v-if="record.editing"
                  v-model="record.planWarehouseId" 
                  @change="(value) => handleWarehouseChangeForRow(record, value)"
                  style="width: 100%" />
                <span v-else>{{ text }}</span>
              </div>
            </template>
            
            <template slot="planLocationSlot" slot-scope="text, record">
              <div class="location-selector-wrapper">
                <j-select-warehouse-location 
                  v-if="record.editing"
                  v-model="record.planLocationId"
                  :warehouse-id="record.planWarehouseId"
                  @change="(value, option) => handleLocationChange(record, value, option)"
                  style="width: 100%"
                  class="location-selector" />
                <span v-else>{{ text }}</span>
              </div>
            </template>
            
            <template slot="actualQuantitySlot" slot-scope="text, record">
              <div>
                <a-input-number 
                  v-if="record.editing"
                  v-model="record.actualQuantity"
                  :min="0"
                  :max="record.planQuantity"
                  :step="0.01"
                  :precision="2"
                  @change="validateActualQuantity(record)"
                  style="width: 100%" />
                <span v-else>{{ text || 0 }}</span>
              </div>
            </template>
            
            <template slot="statusSlot" slot-scope="text, record">
              <a-tag :color="getStatusTagColor(record)">
                {{ getStatusText(record) }}
              </a-tag>
            </template>
            
            <template slot="inboundStatusSlot" slot-scope="text, record">
              <a-tag :color="getInboundStatusColor(record)">
                {{ getInboundStatusText(record) }}
              </a-tag>
            </template>
            
            <template slot="actionSlot" slot-scope="text, record">
              <div>
                <template v-if="record.editing">
                  <a-button type="link" size="small" @click="saveRowEdit(record)">保存</a-button>
                  <a-button type="link" size="small" @click="cancelRowEdit(record)">取消</a-button>
                </template>
                <template v-else>
                  <!-- 未入库或部分入库的明细可以编辑 -->
                  <a-button 
                    v-if="record.inboundStatus !== 'fully'" 
                    type="link" 
                    size="small" 
                    @click="editRow(record)">编辑</a-button>
                  
                  <!-- 已入库的明细可以查看详情 -->
                  <a-button 
                    v-if="record.inboundStatus === 'fully' || record.inboundStatus === 'partially'" 
                    type="link" 
                    size="small" 
                    @click="viewInboundDetail(record)">查看</a-button>
                  
                  <!-- 库位已满按钮只在特定条件下显示 -->
                  <a-button 
                    v-if="record.locationStatus !== '5'" 
                    type="link" 
                    size="small" 
                    @click="addExtraLocation(record)">库位已满</a-button>
                </template>
              </div>
            </template>
          </a-table>
        </div>
      </a-card>
      
      <!-- 底部按钮 -->
      <div class="footer-buttons">
        <a-button @click="handleCancel">关闭</a-button>
        <a-button type="primary" @click="handleBatchSave" :loading="confirmLoading">批量确认入库</a-button>
      </div>
    </a-spin>
  </a-modal>
</template>

<script>
  import { getAction, postAction } from '@/api/manage'
  import { confirmInbound } from '@/api/wms'
  import JSelectWarehouse from '@/components/jeecgbiz/JSelectWarehouse'
  import JSelectWarehouseLocation from '@/components/jeecgbiz/JSelectWarehouseLocation'
  import JDictTag from '@/components/dict/JDictTag'
  import JImageUpload from '@/components/jeecg/JImageUpload'
  
  export default {
    name: "InboundConfirmModal",
    components: {
      JSelectWarehouse,
      JSelectWarehouseLocation,
      JDictTag,
      JImageUpload
    },
    data() {
      return {
        title: "确认入库",
        visible: false,
        inboundOrder: {},
        detailList: [],
        filteredDetailList: [], // 添加过滤后的明细列表
        filterType: 'all', // 默认显示全部明细
        confirmLoading: false,
        loading: false,
        editingActualTime: false,
        editingTotalActualQty: false,
        selectedRowKeys: [],
        columns: [
          { 
            title: '物料编码', 
            dataIndex: 'materialCode', 
            width: 120,
            sorter: (a, b) => a.materialCode.localeCompare(b.materialCode),
            defaultSortOrder: 'ascend'
          },
          { title: '物料名称', dataIndex: 'materialName', width: 150 },
          { title: '物料类型', dataIndex: 'materialType', scopedSlots: { customRender: 'materialTypeSlot' }, width: 100 },
          { title: '规格', dataIndex: 'specification', width: 120 },
          { title: '单位', dataIndex: 'unit', width: 80 },
          { 
            title: '计划入库仓库', 
            dataIndex: 'planWarehouseName', 
            width: 150,
            scopedSlots: { customRender: 'planWarehouseSlot' }
          },
          { 
            title: '计划入库库位', 
            dataIndex: 'planLocationName', 
            width: 220,
            scopedSlots: { customRender: 'planLocationSlot' }
          },
          { title: '计划数量', dataIndex: 'planQuantity', width: 100 },
          { 
            title: '实际数量', 
            dataIndex: 'actualQuantity', 
            width: 120,
            scopedSlots: { customRender: 'actualQuantitySlot' }
          },
          { title: '单位成本', dataIndex: 'unitCost', width: 100 },
          { title: '库位状态', dataIndex: 'locationStatus', scopedSlots: { customRender: 'statusSlot' }, width: 100 },
          { 
            title: '入库状态', 
            dataIndex: 'inboundStatus', 
            width: 100,
            scopedSlots: { customRender: 'inboundStatusSlot' }
          },
          { 
            title: '操作', 
            dataIndex: 'action', 
            scopedSlots: { customRender: 'actionSlot' }, 
            width: 120
          }
        ]
      }
    },
    methods: {
      // 显示确认入库弹窗
      confirm(record) {
        this.visible = true;
        
        // 加载入库单信息和明细
        this.loadInboundOrder(record.id);
      },
      
      // 加载入库单信息
      loadInboundOrder(id) {
        this.loading = true;
        
        // 获取入库单信息
        getAction('/wms/inboundOrder/queryById', { id: id }).then(res => {
          if (res.success) {
            this.inboundOrder = res.result || {};
            console.log('加载入库单信息成功:', this.inboundOrder);
            // 如果没有实际入库时间，设置为当前时间
            if (!this.inboundOrder.actualInboundTime) {
              this.inboundOrder.actualInboundTime = this.formatCurrentDate();
            }
            // 如果没有总实际入库数量，设置为总计划入库数量
            if (!this.inboundOrder.totalActualQuantity && this.inboundOrder.totalPlanQuantity) {
              this.inboundOrder.totalActualQuantity = this.inboundOrder.totalPlanQuantity;
            }
            
            // 加载入库凭证
            if (this.inboundOrder.inboundVoucher) {
              this.loadInboundVoucher(this.inboundOrder.inboundVoucher);
            }
            
            // 加载入库单明细
            this.loadDetailList(id);
          } else {
            this.$message.error(res.message || '获取入库单信息失败');
            this.loading = false;
          }
        }).catch((err) => {
          console.error('加载入库单信息失败:', err);
          this.loading = false;
        });
      },
      
      // 加载入库单明细
      loadDetailList(inboundOrderId) {
        getAction('/wms/inboundOrder/queryDetailList', { 
          inboundOrderId: inboundOrderId,
          showOnlyNotInbound: false, // 修改为false，显示所有明细，包括已入库的
          excludeFullLocation: false // 修改为false，不排除库位已满的明细
        }).then(res => {
          if (res.success) {
            console.log('加载入库单明细成功:', res.result);
            // 为每条明细添加编辑状态标记和入库状态标记
            this.detailList = (res.result || []).map(item => {
              // 计算入库状态
              const inboundStatus = this.calculateInboundStatus(item);
              
              return {
                ...item,
                editing: false,
                originalData: { ...item },
                inboundStatus: inboundStatus
              };
            });
            
            // 按物料编码排序
            this.detailList.sort((a, b) => a.materialCode.localeCompare(b.materialCode));
            
            // 应用过滤
            this.applyFilter();
          } else {
            this.$message.error(res.message || '获取入库单明细失败');
          }
        }).catch((err) => {
          console.error('加载入库单明细失败:', err);
        }).finally(() => {
          this.loading = false;
        });
      },
      
      // 统一计算入库状态的方法
      calculateInboundStatus(detail) {
        const actualQty = parseFloat(detail.actualQuantity || 0);
        const planQty = parseFloat(detail.planQuantity || 0);
        
        // 如果库位状态为已满(5)且有实际入库数量，则视为已完成入库
        if (detail.locationStatus === '5' && actualQty > 0) {
          return '1'; // 已入库
        }
        
        // 如果实际入库数量大于等于计划数量，则视为已完成入库
        if (actualQty >= planQty && actualQty > 0) {
          return '1'; // 已入库
        }
        
        // 如果有实际入库数量但小于计划数量，或者没有实际入库数量，则视为未入库
        return '0'; // 未入库或部分入库
      },
      
      // 更新明细的入库状态
      updateInboundStatus(detail) {
        if (!detail) return;
        
        // 计算并设置入库状态
        detail.inboundStatus = this.calculateInboundStatus(detail);
        return detail.inboundStatus;
      },
      
      // 应用过滤
      applyFilter() {
        if (this.filterType === 'all') {
          this.filteredDetailList = [...this.detailList];
        } else if (this.filterType === 'notInbound') {
          // 显示未入库或部分入库的明细
          this.filteredDetailList = this.detailList.filter(item => 
            item.inboundStatus === '0' || !item.inboundStatus
          );
        } else if (this.filterType === 'inbound') {
          // 只显示已完成入库的明细
          this.filteredDetailList = this.detailList.filter(item => 
            item.inboundStatus === '1'
          );
        }
        
        // 确保过滤后的列表也按物料编码排序
        this.filteredDetailList.sort((a, b) => a.materialCode.localeCompare(b.materialCode));
      },
      
      // 处理过滤变更
      handleFilterChange() {
        this.applyFilter();
        this.selectedRowKeys = []; // 清空选择
      },
      
      // 获取状态颜色
      getStatusColor(status) {
        switch (status) {
          case 1: return 'orange'; // 待入库
          case 2: return 'green';  // 已入库
          case 3: return 'blue';   // 部分入库
          case 9: return 'red';    // 已取消
          default: return 'default';
        }
      },
      
      // 处理取消按钮点击
      handleCancel() {
        this.visible = false;
        this.detailList = [];
        this.inboundOrder = {};
      },
      
      // 处理行编辑
      editRow(record) {
        // 在编辑前，先取消所有其他行的编辑状态
        this.detailList.forEach(item => {
          if (item.id !== record.id && item.editing) {
            this.cancelRowEdit(item);
          }
        });
        
        // 复制当前行数据，以便在编辑时保留原始值
        record.originalData = { ...record };
        
        // 当实际数量为0且库位未满时，默认设置实际数量为计划数量
        const actualQty = parseFloat(record.actualQuantity || 0);
        if (actualQty === 0 && record.locationStatus !== '5') {
          record.actualQuantity = record.planQuantity;
        }
        
        record.editing = true;
        
        // 编辑时暂时移除表格的横向滚动
        this.$nextTick(() => {
          const tableBody = document.querySelector('.ant-table-body');
          if (tableBody) {
            tableBody.style.overflowX = 'hidden';
          }
        });
      },

      // 保存行编辑
      saveRowEdit(record) {
        // 当实际数量为0且库位未满时，默认使用计划数量
        if ((parseFloat(record.actualQuantity || 0) === 0) && record.locationStatus !== '5') {
          record.actualQuantity = record.planQuantity;
          this.$message.info(`实际数量为0，已默认设置为计划数量：${record.planQuantity}`);
        }
        
        // 验证实际数量不超过计划数量
        if (parseFloat(record.actualQuantity || 0) > parseFloat(record.planQuantity || 0)) {
          this.$message.error('实际入库数量不能超过计划入库数量');
          record.actualQuantity = record.planQuantity;
          return;
        }
        
        // 构建更新参数
        const params = {
          id: record.id,
          planWarehouseId: record.planWarehouseId,
          planLocationId: record.planLocationId,
          actualQuantity: record.actualQuantity || 0,
          // 设置实际入库仓库和库位与计划相同
          actualWarehouseId: record.planWarehouseId,
          actualLocationId: record.planLocationId,
          updateInventory: false // 始终设置为false，表示仅更新明细，不更新库存
        };
        
        // 计算入库状态
        const actualQty = parseFloat(record.actualQuantity || 0);
        const planQty = parseFloat(record.planQuantity || 0);
        
        // 更新入库状态
        const inboundStatus = this.updateInboundStatus(record);
        
        // 如果是全部入库状态，添加额外参数
        if (inboundStatus === '1') { // 已入库
          params.inboundStatus = '1'; // 设置为已入库状态(1)
          params.inboundOrderId = this.inboundOrder.id;
          params.materialCode = record.materialCode;
        }
        
        // 当实际数量不等于0且库位状态不等于5时，设置库位状态为"占用(2)"
        if (actualQty > 0 && record.locationStatus !== '5') {
          params.updateLocationStatus = true;
          params.locationStatus = '2'; // 设置为"占用(2)"
          params.updateInventory = false // 确保不更新库存
        }
        
        this.confirmLoading = true;
        
        // 如果是额外库位，则创建新记录
        if (record.isExtra) {
          // 添加入库单ID和原始明细ID
          params.inboundOrderId = this.inboundOrder.id; // 确保使用正确的入库单ID
          params.originalDetailId = record.originalData ? record.originalData.id : null;
          params.materialId = record.materialId;
          params.materialCode = record.materialCode;
          params.materialName = record.materialName;
          params.materialType = record.materialType;
          params.specification = record.specification;
          params.unit = record.unit;
          params.unitCost = record.unitCost;
          params.planQuantity = record.planQuantity; // 确保传递计划数量
          params.updateInventory = false; // 额外库位明细也不更新库存
          
          console.log('创建额外库位明细参数:', params); // 添加日志，便于调试
          
          // 调用创建接口
          postAction('/wms/inboundOrder/addExtraLocationDetail', params).then(res => {
            if (res.success) {
              this.$message.success('添加额外库位成功');
              record.editing = false;
              // 更新原始数据
              record.originalData = { ...record };
              // 重新加载数据
              this.loadInboundOrder(this.inboundOrder.id);
              // 恢复表格横向滚动
              this.restoreTableScroll();
              // 检查入库单状态
              this.checkAndUpdateOrderStatus();
            } else {
              this.$message.error(res.message || '添加额外库位失败');
            }
          }).catch(() => {
            this.$message.error('添加额外库位失败');
          
          }).finally(() => {
            this.confirmLoading = false;
          });
          return;
        }
        
        // 调用更新接口
        postAction('/wms/inboundOrder/updateDetail', params).then(res => {
          if (res.success) {
            this.$message.success('保存成功');
            record.editing = false;
            // 更新原始数据
            record.originalData = { ...record };
            
            // 重新加载数据
            this.loadInboundOrder(this.inboundOrder.id);
            // 恢复表格横向滚动
            this.restoreTableScroll();
            
            // 检查是否所有明细都已完成入库
            this.checkAndUpdateOrderStatus();
          } else {
            this.$message.error(res.message || '保存失败');
          }
        }).catch(() => {
          this.$message.error('保存失败');
        }).finally(() => {
          this.confirmLoading = false;
        });
      },

      // 取消行编辑
      cancelRowEdit(record) {
        record.editing = false;
        // 恢复原始数据
        Object.assign(record, record.originalData);
        // 恢复表格横向滚动
        this.restoreTableScroll();
      },

      // 恢复表格横向滚动
      restoreTableScroll() {
        this.$nextTick(() => {
          const tableBody = document.querySelector('.ant-table-body');
          if (tableBody) {
            tableBody.style.overflowX = 'auto';
          }
        });
      },

      // 获取行样式类名
      getRowClassName(record) {
        let className = record.editing ? 'editable-row editing-row' : 'editable-row';
        
        // 根据入库状态添加不同的样式
        if (record.inboundStatus === '1') { // 已入库
          className += ' fully-inbound-row';
        } else if (record.inboundStatus === '0') { // 未入库或部分入库
          className += ' partially-inbound-row';
        }
        
        return className;
      },

      // 处理额外库位
      addExtraLocation(record) {
        // 检查计划数量和实际数量
        const actualQty = parseFloat(record.actualQuantity || 0);
        const planQty = parseFloat(record.planQuantity || 0);
        
        // 验证实际数量不超过计划数量
        if (actualQty > planQty) {
          this.$message.error('实际入库数量不能超过计划入库数量');
          return;
        }
        
        // 计算剩余待入库数量
        const remainingQty = planQty - actualQty;
        
        // 准备更新参数，但不立即标记原记录库位已满，等确认后再标记
        const updateParams = {
          id: record.id,
          locationFull: true,
          planLocationId: record.planLocationId, // 确保传递planLocationId参数，用于更新库位状态
          locationStatus: '5', // 设置库位状态为已满
          updateLocationStatus: true, // 添加此参数，指示后端需要更新库位状态
          updateInventory: false // 添加此参数，指示后端不更新库存
        };
        
        // 如果剩余数量为0或负数，只进行库位状态修改，不需要创建新明细
        if (remainingQty <= 0) {
          // 添加入库状态为全部入库
          updateParams.inboundStatus = '1'; // 设置为已入库状态(1)
          // 添加入库单ID和物料编号，用于后端查询并更新相同物料的其他明细
          updateParams.inboundOrderId = this.inboundOrder.id;
          updateParams.materialCode = record.materialCode;
          
          // 显示确认对话框
          this.$confirm({
            title: '确认库位已满',
            content: `当前物料 ${record.materialName}(${record.materialCode}) 的计划数量已全部入库，确认标记库位已满吗？`,
            okText: '确认',
            cancelText: '取消',
            onOk: () => {
              // 只有确认后才标记库位已满
              record.locationFull = true;
              
              // 调用更新接口，将库位状态更新为已满
              this.confirmLoading = true;
              postAction('/wms/inboundOrder/updateDetail', updateParams).then(res => {
                if (res.success) {
                  this.$message.success('标记库位已满成功，库位状态已更新为"已满(5)"');
                  
                  // 从列表中移除该记录，因为库位已满
                  const index = this.detailList.findIndex(item => item.id === record.id);
                  if (index !== -1) {
                    this.detailList.splice(index, 1);
                    // 如果该行在选中状态，从选中行中移除
                    const selectedIndex = this.selectedRowKeys.indexOf(record.id);
                    if (selectedIndex !== -1) {
                      this.selectedRowKeys.splice(selectedIndex, 1);
                    }
                  }
                  
                  this.$message.info('计划数量已全部入库，库位已标记为已满');
                  // 重新加载数据以更新状态
                  this.loadInboundOrder(this.inboundOrder.id);
                  // 发送成功事件给父组件
                  this.$emit('ok');
                  // 检查是否所有明细都已完成入库
                  this.checkAndUpdateOrderStatus();
                  // 延迟一秒后关闭模态框
                  setTimeout(() => {
                    this.handleCancel();
                  }, 1000);
                } else {
                  this.$message.error(res.message || '标记库位已满失败');
                }
              }).catch(error => {
                this.$message.error('标记库位已满失败: ' + (error.message || error));
              }).finally(() => {
                this.confirmLoading = false;
              });
            }
          });
          return;
        }
        
        // 如果计划数量不等于实际数量，则需要创建新明细
        // 显示确认对话框
        this.$confirm({
          title: '确认库位已满',
          content: `当前物料 ${record.materialName}(${record.materialCode}) 的计划数量为 ${planQty}，实际入库数量为 ${actualQty}，
                    确认标记库位已满并创建新明细以容纳剩余数量 ${remainingQty} ${record.unit} 吗？`,
          okText: '确认',
          cancelText: '取消',
          onOk: () => {
            // 只有确认后才标记库位已满
            record.locationFull = true;
            
            // 调用更新接口，将库位状态更新为已满
            this.confirmLoading = true;
            postAction('/wms/inboundOrder/updateDetail', updateParams).then(res => {
              if (res.success) {
                this.$message.success('标记库位已满成功，库位状态已更新为"已满(5)"');
                
                // 从列表中移除该记录，因为库位已满
                const index = this.detailList.findIndex(item => item.id === record.id);
                if (index !== -1) {
                  this.detailList.splice(index, 1);
                  // 如果该行在选中状态，从选中行中移除
                  const selectedIndex = this.selectedRowKeys.indexOf(record.id);
                  if (selectedIndex !== -1) {
                    this.selectedRowKeys.splice(selectedIndex, 1);
                  }
                }
                
                // 复制当前行数据，创建新明细
                const newRecord = { 
                  ...record,
                  // 必要的字段
                  inboundOrderId: this.inboundOrder.id, // 确保使用正确的入库单ID，而不是record.inboundOrderId
                  materialId: record.materialId,
                  materialCode: record.materialCode,
                  materialName: record.materialName,
                  materialType: record.materialType,
                  specification: record.specification,
                  unit: record.unit,
                  unitCost: record.unitCost,
                  // 设置计划数量为剩余未入库数量
                  planQuantity: remainingQty,
                  // 清除实际入库数据
                  actualQuantity: 0,
                  // 清除库位信息，确保新明细的库位为空闲状态
                  planWarehouseId: record.planWarehouseId, // 保留原仓库ID
                  planWarehouseName: record.planWarehouseName, // 保留原仓库名称
                  planLocationId: null, // 清空库位ID
                  planLocationName: '', // 清空库位名称
                  // 清除状态信息
                  locationFull: false,
                  locationStatus: null,
                  originalDetailId: record.id,//原始明细ID
                  inboundStatus: '0', // 设置为未入库状态
                  availableLocations: [] // 初始化可用库位列表
                };
                
                // 清除id，确保创建新记录
                delete newRecord.id;
                
                // 清除编辑状态和原始数据
                delete newRecord.editing;
                delete newRecord.originalData;
                
                // 设置为编辑状态
                newRecord.editing = true;
                newRecord.isExtra = true;  // 标记为额外库位
                newRecord.originalDetailId = record.id; // 记录原明细ID
                newRecord.originalData = { ...newRecord };
                
                // 查询可用库位
                this.queryAvailableLocationsForNewRecord(newRecord);
                
                // 添加到明细列表
                this.detailList.push(newRecord);
                
                // 应用过滤以确保新明细显示在列表中
                this.applyFilter();
                
                // 滚动到底部
                this.$nextTick(() => {
                  const container = document.querySelector('.table-container');
                  if (container) {
                    container.scrollTop = container.scrollHeight;
                  }
                });
                
                this.$message.info(`已创建额外库位明细，请选择新库位并保存，剩余待入库数量: ${remainingQty} ${record.unit}`);
                
                // 检查并更新入库单状态
                this.checkAndUpdateOrderStatus();
              } else {
                this.$message.error(res.message || '标记库位已满失败');
              }
            }).catch(error => {
              this.$message.error('标记库位已满失败: ' + (error.message || error));
            }).finally(() => {
              this.confirmLoading = false;
            });
          }
        });
      },
      
      // 为新记录查询可用库位
      queryAvailableLocationsForNewRecord(record) {
        if (!record || !record.planWarehouseId) {
          console.warn('无法查询可用库位：缺少仓库ID');
          return;
        }
        
        this.$message.loading(`正在查询仓库可用库位...`);
        
        const materialType = record.materialType || '4'; // 默认为其他物料类型
        
        // 调用后端接口查询可用库位
        getAction('/wms/location/queryAvailableLocations', {
          warehouseId: record.planWarehouseId,
          materialType: materialType
        }).then(res => {
          if (res.success && res.result && res.result.length > 0) {
            // 保存可用库位列表
            record.availableLocations = res.result.map(location => ({
              id: location.id,
              locationName: location.locationName,
              locationCode: location.locationCode,
              status: location.status
            }));
            
            // 自动选择第一个可用库位
            const firstLocation = res.result[0];
            record.planLocationId = firstLocation.id;
            record.planLocationName = firstLocation.locationName;
            
            this.$message.success(`已找到${res.result.length}个可用库位`);
          } else {
            // 类型不匹配或没有找到库位时，尝试查询空库位
            this.$message.info('正在查询空库位...');
            
            // 查询空库位
            getAction('/wms/location/queryEmptyLocations', {
              warehouseId: record.planWarehouseId
            }).then(emptyRes => {
              if (emptyRes.success && emptyRes.result && emptyRes.result.length > 0) {
                // 保存可用库位列表
                record.availableLocations = emptyRes.result.map(location => ({
                  id: location.id,
                  locationName: location.locationName,
                  locationCode: location.locationCode,
                  status: location.status
                }));
                
                // 自动选择第一个可用库位
                const firstLocation = emptyRes.result[0];
                record.planLocationId = firstLocation.id;
                record.planLocationName = firstLocation.locationName;
                
                this.$message.success(`已找到${emptyRes.result.length}个空库位`);
              } else {
                this.$message.warning('没有找到可用的库位，请手动选择库位');
                record.availableLocations = [];
              }
            }).catch(err => {
              console.error('查询空库位失败:', err);
              this.$message.error('查询空库位失败');
            });
          }
        }).catch(err => {
          console.error('查询可用库位失败:', err);
          this.$message.error('查询可用库位失败');
        }).finally(() => {
          this.$message.destroy(); // 关闭加载提示
        });
      },

      // 处理行仓库选择变更
      handleWarehouseChangeForRow(record, value) {
        record.planWarehouseId = value;
        record.planLocationId = undefined; // 清空库位
        record.planLocationName = '';
      },
      
      // 处理库位选择变更
      handleLocationChange(record, value, option) {
        if (!record || !value) return;
        
        // 更新物料的库位信息
        record.planLocationId = value;
        
        // 尝试从option获取库位名称
        if (option && option.componentOptions && option.componentOptions.children && option.componentOptions.children[0]) {
          record.planLocationName = option.componentOptions.children[0].text;
        } else if (option && option.title) {
          record.planLocationName = option.title;
        } else {
          // 如果无法从option获取名称，则从record.availableLocations中查找
          if (record.availableLocations && record.availableLocations.length > 0) {
            const location = record.availableLocations.find(loc => loc.id === value);
            if (location) {
              record.planLocationName = location.locationName;
            }
          }
        }
        
        console.log('库位已更新:', record.planLocationName, '(ID:', value, ')');
      },

      // 批量确认入库
      handleBatchSave() {
        if (this.selectedRowKeys.length === 0) {
          this.$message.warning('请选择要批量确认入库的明细');
          return;
        }

        const selectedDetails = this.detailList.filter(item => this.selectedRowKeys.includes(item.id));
        
        // 不再过滤已完全入库的明细，允许用户确认所有选中的明细
        const detailsToConfirm = selectedDetails;
        
        if (detailsToConfirm.length === 0) {
          this.$message.warning('请选择要确认入库的明细');
          return;
        }

        // 统计不同状态的明细数量
        const fullyInboundCount = selectedDetails.filter(item => item.inboundStatus === '1').length; // 已入库
        const partiallyInboundCount = selectedDetails.filter(item => item.inboundStatus === '0').length; // 未入库或部分入库
        const notInboundCount = selectedDetails.filter(item => item.inboundStatus === '0').length; // 未入库
        
        // 显示确认对话框
        this.$confirm({
          title: '确认批量入库',
          width: 500,
          content: h => {
            return h('div', [
              h('p', `您已选择 ${selectedDetails.length} 条明细，其中：`),
              h('ul', [
                h('li', `已完成入库: ${fullyInboundCount} 条`),
                h('li', `未入库: ${notInboundCount} 条`)
              ]),
              h('p', `将要确认入库的明细: ${detailsToConfirm.length} 条`),
              h('p', { style: { color: '#ff4d4f' } }, '注意: 此操作将更新库存信息，请确认数据无误')
            ]);
          },
          okText: '确认入库',
          cancelText: '取消',
          onOk: () => {
            this.confirmBatchSave(detailsToConfirm);
          }
        });
      },
      
      // 执行批量确认入库
      confirmBatchSave(detailsToConfirm) {
        // 构建批量确认参数
        const confirmDetails = detailsToConfirm.map(item => {
          // 当实际数量为0且库位未满时，默认使用计划数量
          let actualQty = parseFloat(item.actualQuantity || 0);
          if (actualQty === 0 && item.locationStatus !== '5') {
            actualQty = parseFloat(item.planQuantity || 0);
            item.actualQuantity = actualQty; // 更新item的实际数量
          } else {
            // 如果没有设置实际数量，默认使用计划数量
            actualQty = actualQty || parseFloat(item.planQuantity || 0);
          }
          
          const params = {
            id: item.id,
            actualWarehouseId: item.planWarehouseId, // 使用计划仓库作为实际仓库
            actualLocationId: item.planLocationId, // 使用计划库位作为实际库位
            actualQuantity: actualQty,
            remark: item.remark || '',
            // 添加计划数量，用于后端计算入库状态
            planQuantity: item.planQuantity,
            // 添加物料编码，用于后端更新相同物料的其他明细
            materialCode: item.materialCode,
            // 添加物料ID，用于后端更新库存
            materialId: item.materialId,
            // 添加单位成本，用于后端更新库存成本
            unitCost: item.unitCost,
            // 添加标记，表示需要更新库存
            updateInventory: true
          };
          
          // 当实际数量大于0且库位状态不是已满时，设置库位状态为"占用(2)"
          if (actualQty > 0 && item.locationStatus !== '5') {
            params.updateLocationStatus = true;
            params.locationStatus = '2'; // 设置为"占用(2)"
          }
          
          return params;
        });

        this.confirmLoading = true;
        postAction('/wms/inboundOrder/batchConfirmInboundWithBody', {
          inboundOrderId: this.inboundOrder.id,
          details: confirmDetails
        }).then(res => {
          if (res.success) {
            this.$message.success('批量确认入库成功');
            
            // 更新明细状态
            detailsToConfirm.forEach(item => {
              // 如果没有设置实际数量，默认使用计划数量
              if (!item.actualQuantity) {
                item.actualQuantity = item.planQuantity;
              }
              
              // 更新入库状态
              this.updateInboundStatus(item);
              
              // 如果已完全入库，从列表中移除
              if (item.inboundStatus === '1') { // 已入库
                const index = this.detailList.findIndex(detail => detail.id === item.id);
                if (index !== -1) {
                  this.detailList.splice(index, 1);
                }
              }
            });
            
            this.selectedRowKeys = []; // 清空选择
            this.loadInboundOrder(this.inboundOrder.id); // 重新加载数据
            this.$emit('ok'); // 通知父组件刷新列表
            // 检查是否所有明细都已完成入库
            this.checkAndUpdateOrderStatus();
            this.handleCancel(); // 关闭模态框
          } else {
            this.$message.error(res.message || '批量确认入库失败');
          }
        }).finally(() => {
          this.confirmLoading = false;
        });
      },

      // 选择行变更
      onSelectChange(selectedRowKeys) {
        this.selectedRowKeys = selectedRowKeys;
      },

      // 获取状态标签颜色
      getStatusTagColor(record) {
        //record.locationStatus 空闲	1, 占用	2 ,锁定	3, 禁用	4,已满	5
        if(record.locationStatus == '1'){
          return 'orange';
        }else if(record.locationStatus == '2'){
          return 'blue';
        }else if(record.locationStatus == '3'){
          return 'purple';
        }else if(record.locationStatus == '4'){
          return 'red';
        }else if(record.locationStatus == '5'){
          return 'gray';
        }else{
          return 'default';
        }
      },

      // 获取状态文本 locationStatus 空闲	1 占用	2 锁定	3 禁用	4 已满	5
      getStatusText(record) {
        if(record.locationStatus == '1'){
          return '空闲';
        }else if(record.locationStatus == '2'){
          return '占用';
        }else if(record.locationStatus == '3'){
          return '锁定';
        }else if(record.locationStatus == '4'){
          return '禁用';
        }else if(record.locationStatus == '5'){
          return '已满';
        }else{
          return '默认';
        }
      },

      // 添加获取入库状态颜色方法
      getInboundStatusColor(record) {
        if (record.inboundStatus === '1') { // 已入库
          return 'green';
        } else if (record.inboundStatus === '0') { // 未入库或部分入库
          return 'blue';
        } else {
          return 'default';
        }
      },
      
      // 添加获取入库状态文本方法
      getInboundStatusText(record) {
        if (record.inboundStatus === '1') { // 已入库
          return '已入库';
        } else if (record.inboundStatus === '0') { // 未入库
          return '未入库';
        } else {
          return '未知';
        }
      },
      
      // 查看入库详情
      viewInboundDetail(record) {
        // 显示入库详情信息
        this.$confirm({
          title: '入库详情',
          width: 600,
          content: h => {
            return h('div', [
              h('p', [h('strong', '物料：'), record.materialName + ' (' + record.materialCode + ')']),
              h('p', [h('strong', '规格：'), record.specification]),
              h('p', [h('strong', '计划数量：'), record.planQuantity + ' ' + record.unit]),
              h('p', [h('strong', '实际数量：'), (record.actualQuantity || 0) + ' ' + record.unit]),
              h('p', [h('strong', '计划仓库/库位：'), record.planWarehouseName + ' / ' + record.planLocationName]),
              h('p', [h('strong', '实际仓库/库位：'), (record.actualWarehouseName || record.planWarehouseName) + ' / ' + (record.actualLocationName || record.planLocationName)]),
              h('p', [h('strong', '单位成本：'), record.unitCost || 0]),
              h('p', [h('strong', '库位状态：'), this.getStatusText(record)]),
              h('p', [h('strong', '入库状态：'), this.getInboundStatusText(record)])
            ]);
          },
          okText: '关闭',
          cancelButtonProps: { style: { display: 'none' } }
        });
      },
      
      // 检查是否显示额外库位按钮
      canShowExtraLocationButton(record) {
        // 显示条件：不是编辑状态、不是额外库位、库位未满、库位状态不是已满(5)或锁定(3)、不是已完全入库
        return !record.editing && 
               !record.locationFull && 
               !record.isExtra &&
               record.locationStatus !== '5' && 
               record.locationStatus !== '3' &&
               record.inboundStatus !== '1'; // 已入库
      },

      // 添加验证实际数量的方法
      validateActualQuantity(record) {
        if (record.actualQuantity > record.planQuantity) {
          this.$message.warning('实际入库数量不能超过计划入库数量');
          record.actualQuantity = record.planQuantity;
        }
      },

      // 格式化当前日期为YYYY-MM-DD HH:mm:ss格式
      formatCurrentDate() {
        const now = new Date();
        const year = now.getFullYear();
        const month = String(now.getMonth() + 1).padStart(2, '0');
        const day = String(now.getDate()).padStart(2, '0');
        const hours = String(now.getHours()).padStart(2, '0');
        const minutes = String(now.getMinutes()).padStart(2, '0');
        const seconds = String(now.getSeconds()).padStart(2, '0');
        return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
      },
      
      // 编辑实际入库时间
      editActualTime() {
        this.editingActualTime = true;
      },
      
      // 保存实际入库时间
      saveActualTime(date, dateString) {
        this.inboundOrder.actualInboundTime = dateString;
        this.editingActualTime = false;
        this.updateInboundOrderInfo();
      },
      
      // 取消编辑实际入库时间
      cancelEditActualTime() {
        this.editingActualTime = false;
      },
      
      // 编辑总实际入库数量
      editTotalActualQty() {
        this.editingTotalActualQty = true;
      },
      
      // 保存总实际入库数量
      saveTotalActualQty() {
        // 验证总实际入库数量不超过总计划入库数量
        if (parseFloat(this.inboundOrder.totalActualQuantity) > parseFloat(this.inboundOrder.totalPlanQuantity)) {
          this.$message.warning('总实际入库数量不能超过总计划入库数量');
          this.inboundOrder.totalActualQuantity = this.inboundOrder.totalPlanQuantity;
        }
        this.editingTotalActualQty = false;
        this.updateInboundOrderInfo();
      },
      
      // 取消编辑总实际入库数量
      cancelEditTotalActualQty() {
        this.editingTotalActualQty = false;
      },
      
      // 更新入库单基本信息
      updateInboundOrderInfo() {
        // 确保inboundVoucher是字符串
        let inboundVoucher = this.inboundOrder.inboundVoucher;
        if (typeof inboundVoucher !== 'string') {
          if (Array.isArray(inboundVoucher)) {
            inboundVoucher = inboundVoucher.map(item => {
              if (typeof item === 'string') return item;
              if (item && item.response && item.response.message) return item.response.message;
              return '';
            }).filter(Boolean).join(',');
          } else if (inboundVoucher && inboundVoucher.response && inboundVoucher.response.message) {
            inboundVoucher = inboundVoucher.response.message;
          } else {
            inboundVoucher = '';
          }
        }

        const params = {
          id: this.inboundOrder.id,
          actualInboundTime: this.inboundOrder.actualInboundTime,
          totalActualQuantity: this.inboundOrder.totalActualQuantity,
          inboundVoucher: inboundVoucher
        };
        
        postAction('/wms/inboundOrder/updateBasicInfo', params).then(res => {
          if (res.success) {
            this.$message.success('更新成功');
          } else {
            this.$message.error(res.message || '更新失败');
          }
        }).catch(() => {
          this.$message.error('更新失败');
        });
      },
      
      // 处理凭证变更
      handleVoucherChange(fileList) {
        console.log('入库凭证变更:', fileList);
        
        // 当returnUrl为true时，fileList是字符串路径
        if (typeof fileList === 'string') {
          // 直接保存字符串路径
          this.inboundOrder.inboundVoucher = fileList;
          console.log('保存入库凭证路径:', this.inboundOrder.inboundVoucher);
        } else if (Array.isArray(fileList)) {
          // 如果是数组，转换为字符串路径
          const paths = fileList.map(file => {
            if (file && typeof file === 'object' && file.response && file.response.message) {
              return file.response.message;
            } else if (file && typeof file === 'string') {
              return file;
            }
            return '';
          }).filter(Boolean).join(',');
          
          this.inboundOrder.inboundVoucher = paths;
          console.log('转换后的入库凭证路径:', this.inboundOrder.inboundVoucher);
        } else {
          // 其他情况，设为空字符串
          console.warn('入库凭证格式不正确:', fileList);
          this.inboundOrder.inboundVoucher = '';
        }
        
        this.updateInboundOrderInfo();
      },
      
      // 处理图片加载错误
      handleImageError(e) {
        console.error('图片加载失败:', e);
        e.target.style.display = 'none';
        const container = e.target.parentNode;
        if (container) {
          const icon = document.createElement('i');
          icon.className = 'anticon anticon-picture';
          icon.style.fontSize = '24px';
          icon.style.color = '#d9d9d9';
          container.insertBefore(icon, e.target);

          const errorText = document.createElement('div');
          errorText.innerText = '图片不存在';
          errorText.style.color = '#ff4d4f';
          errorText.style.fontSize = '12px';
          errorText.style.marginTop = '4px';
          container.appendChild(errorText);
        }
      },
      
      // 加载入库凭证
      loadInboundVoucher(voucher) {
        if (!voucher) {
          console.log('没有入库凭证数据');
          return;
        }
        
        try {
          console.log('加载入库凭证:', voucher);
          
          // 如果voucher是对象，避免[object Object]错误
          if (typeof voucher === 'object') {
            console.warn('凭证路径不应该是对象:', JSON.stringify(voucher));
            return;
          }
          
          // 处理多个图片路径
          const imageArray = typeof voucher === 'string' ? voucher.split(',') : [];
          
          // 设置文件列表
          this.inboundOrder.inboundVoucher = voucher; // 直接使用原始字符串
          console.log('设置入库凭证路径:', this.inboundOrder.inboundVoucher);
        } catch (error) {
          console.error('加载入库凭证失败:', error, '原始数据:', voucher);
        }
      },

      // 检查并更新入库单状态
      checkAndUpdateOrderStatus() {
        // 重新加载入库单信息，确保获取最新的状态
        getAction('/wms/inboundOrder/queryById', { id: this.inboundOrder.id }).then(res => {
          if (res.success) {
            const updatedInboundOrder = res.result || {};
            // 如果总实际入库数量发生变化，更新入库单基本信息
            if (updatedInboundOrder.totalActualQuantity !== this.inboundOrder.totalActualQuantity) {
              this.inboundOrder.totalActualQuantity = updatedInboundOrder.totalActualQuantity;
              this.updateInboundOrderInfo(); // 更新总实际入库数量
            }
            // 如果入库状态发生变化，重新计算并更新所有明细的入库状态
            if (updatedInboundOrder.status !== this.inboundOrder.status) {
              this.inboundOrder.status = updatedInboundOrder.status;
              this.detailList.forEach(item => {
                this.updateInboundStatus(item);
              });
              this.applyFilter(); // 重新应用过滤，确保所有明细都正确显示
            }
          } else {
            this.$message.error(res.message || '获取入库单信息失败');
          }
        }).catch((err) => {
          console.error('检查入库单状态失败:', err);
        });
      }
    }
  }
</script>

<style scoped>
.ant-descriptions-bordered .ant-descriptions-item-label {
  background-color: #fafafa;
  font-weight: bold;
}

/* 表格容器样式 */
.table-container {
  max-height: 300px;
  overflow: auto;
}

/* 表格滚动条样式 */
.ant-table-wrapper {
  overflow-x: auto;
}

/* 修复表格滚动条问题，确保滚动条固定在表格底部 */
:deep(.ant-table-body) {
  overflow-x: auto !important;
  overflow-y: auto !important;
}

:deep(.ant-table-fixed-header .ant-table-scroll .ant-table-header) {
  overflow: hidden !important;
  margin-bottom: 0 !important;
  padding-bottom: 0 !important;
}

:deep(.ant-table-body-inner) {
  height: auto !important;
}

/* 表格滚动条样式 */
.table-container::-webkit-scrollbar,
.ant-table-wrapper::-webkit-scrollbar,
:deep(.ant-table-body)::-webkit-scrollbar {
  width: 8px;
  height: 8px;
}

.table-container::-webkit-scrollbar-track,
.ant-table-wrapper::-webkit-scrollbar-track,
:deep(.ant-table-body)::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 4px;
}

.table-container::-webkit-scrollbar-thumb,
.ant-table-wrapper::-webkit-scrollbar-thumb,
:deep(.ant-table-body)::-webkit-scrollbar-thumb {
  background: #ccc;
  border-radius: 4px;
}

.table-container::-webkit-scrollbar-thumb:hover,
.ant-table-wrapper::-webkit-scrollbar-thumb:hover,
:deep(.ant-table-body)::-webkit-scrollbar-thumb:hover {
  background: #aaa;
}

/* 底部按钮样式 */
.footer-buttons {
  text-align: right;
  margin-top: 16px;
}

.footer-buttons button {
  margin-left: 8px;
}

/* 编辑状态下隐藏横向滚动条 */
.editing-row .ant-table-row-cell-break-word {
  white-space: normal !important;
}

/* 编辑行样式 */
.editable-row {
  height: 46px;
}

.editing-row {
  background-color: #f0f7ff;
}

/* 入库状态行样式 */
.fully-inbound-row {
  background-color: #f6ffed;
}

.partially-inbound-row {
  background-color: #e6f7ff;
}

/* 表格单元格样式 */
:deep(.ant-table-tbody > tr > td) {
  padding: 8px;
  vertical-align: middle;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  text-align: center; /* 添加居中显示 */
}

/* 表头居中显示 */
:deep(.ant-table-thead > tr > th) {
  text-align: center;
}

/* 确保编辑状态下的输入框宽度一致 */
:deep(.ant-input-number), :deep(.ant-select) {
  width: 100% !important;
}

/* 库位选择器样式 */
.location-selector-wrapper {
  width: 100%;
  position: relative;
}

.location-selector {
  width: 100% !important;
}

/* 修复下拉菜单样式 */
:deep(.ant-select-dropdown) {
  z-index: 1050;
  max-width: none !important;
  width: auto !important;
}

:deep(.location-selector .ant-select-dropdown) {
  min-width: 180px !important;
}

/* 表格操作区样式 */
.table-operations {
  margin-bottom: 16px;
  display: flex;
  align-items: center;
}
</style> 